#!/usr/bin/env node

/**
 * 关联正确的用户ID到admin账号
 * 用户ID: oPOlNvkKFRjdTazLzUq6D2sHunp0 (微信openId)
 */

const AdminModel = require('./model/admin_model.js');
const UserModel = require('./model/user_model.js');
const timeUtil = require('../framework/utils/time_util.js');

async function linkCorrectUserToAdmin() {
    try {
        console.log('=== 关联正确的用户ID到admin账号 ===');
        
        const userId = 'oPOlNvkKFRjdTazLzUq6D2sHunp0'; // 微信openId
        const adminId = 'admin_001';
        
        console.log('用户ID (openId):', userId);
        console.log('Admin ID:', adminId);
        
        // 首先检查用户是否存在
        const user = await UserModel.getOne({
            _id: userId
        });

        if (!user) {
            console.log('❌ 用户不存在，无法关联');
            return {
                success: false,
                message: '用户不存在'
            };
        }

        console.log('✅ 用户存在:', user.nickName);

        // 检查admin账号是否存在
        const admin = await AdminModel.getOne({
            ADMIN_ID: adminId,
            ADMIN_STATUS: 1
        });

        if (!admin) {
            console.log('❌ Admin账号不存在，正在创建...');
            
            // 创建admin账号
            const adminData = {
                ADMIN_ID: adminId,
                ADMIN_NAME: 'admin',
                ADMIN_PHONE: '13900000000',
                ADMIN_STATUS: 1,
                ADMIN_TYPE: 1,
                ADMIN_LOGIN_CNT: 0,
                ADMIN_LOGIN_TIME: 0,
                ADMIN_TOKEN: '',
                ADMIN_TOKEN_TIME: 0,
                ADMIN_ADD_TIME: timeUtil.time(),
                ADMIN_EDIT_TIME: timeUtil.time(),
                
                linkedUserId: userId,
                linkedStoreIds: [],
                permissions: {
                    device_management: true,
                    store_management: true,
                    user_management: true,
                    order_management: true,
                    payment_management: true,
                    statistics: true,
                    system_settings: true
                },
                lastLoginDevice: '',
                isActive: true,
                role: 'super_admin',
                description: '超级管理员账号'
            };
            
            const result = await AdminModel.insert(adminData);
            console.log('✅ Admin账号创建成功:', result.id);
        } else {
            console.log('✅ Admin账号已存在:', admin.ADMIN_ID);
            
            // 检查是否已经关联了正确的用户
            if (admin.linkedUserId === userId) {
                console.log('✅ Admin账号已正确关联用户');
            } else {
                // 更新admin账号关联信息
                const updateData = {
                    linkedUserId: userId,
                    linkedStoreIds: admin.linkedStoreIds || [],
                    permissions: admin.permissions || {
                        device_management: true,
                        store_management: true,
                        user_management: true,
                        order_management: true,
                        payment_management: true,
                        statistics: true,
                        system_settings: true
                    },
                    ADMIN_EDIT_TIME: timeUtil.time()
                };

                await AdminModel.edit({
                    ADMIN_ID: adminId
                }, updateData);
                
                console.log('✅ Admin账号关联信息更新成功');
            }
        }
        
        // 注意：不需要更新用户表，只需要更新admin表的linkedUserId字段
        console.log('✅ 无需更新用户表，直接通过admin表关联');
        
        // 验证关联结果
        const verifyAdmin = await AdminModel.getOne({
            ADMIN_ID: adminId,
            linkedUserId: userId,
            ADMIN_STATUS: 1,
            isActive: true
        });
        
        if (verifyAdmin) {
            console.log('✅ 验证成功：用户已正确关联到admin账号');
            console.log('Admin信息:', {
                adminId: verifyAdmin.ADMIN_ID,
                adminName: verifyAdmin.ADMIN_NAME,
                linkedUserId: verifyAdmin.linkedUserId,
                role: verifyAdmin.role,
                permissions: verifyAdmin.permissions
            });
        } else {
            console.log('❌ 验证失败：用户未正确关联');
        }
        
        console.log('=== 关联完成 ===');
        
        return {
            success: true,
            message: '用户关联成功',
            userId: userId,
            adminId: adminId,
            userNickName: user.nickName
        };
        
    } catch (error) {
        console.error('❌ 关联用户失败:', error);
        return {
            success: false,
            message: '关联失败: ' + error.message
        };
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    linkCorrectUserToAdmin().then(result => {
        console.log('最终结果:', result);
        process.exit(result.success ? 0 : 1);
    }).catch(error => {
        console.error('脚本执行失败:', error);
        process.exit(1);
    });
}

module.exports = { linkCorrectUserToAdmin };
